<template>
  <div class="app-container p-6">
    <!-- 页面标题和操作按钮 - 完全匹配原型 -->
    <div class="page-header-section flex flex-col md:flex-row md:items-center md:justify-between mb-6">
      <div class="page-title-area">
        <h1 class="text-2xl font-bold text-text-primary">角色管理</h1>
        <p class="text-text-muted mt-2">管理系统中的所有角色，包括创建、编辑、删除和配置权限</p>
      </div>
      <div class="page-actions-area mt-4 md:mt-0">
        <!-- 主要操作按钮 -->
        <button
          @click="handleAdd"
          v-permission="'role:create'"
          class="primary-action-btn bg-primary hover:bg-primary-hover text-white px-6 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-plus mr-2"></i>
          <span>新增角色</span>
        </button>
      </div>
    </div>

    <!-- 搜索和筛选区域 - 完全匹配原型样式 -->
    <div class="search-form-card bg-panel rounded-lg shadow-card p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <!-- 角色名称搜索 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">角色名称</label>
          <div class="relative">
            <input
              type="text"
              v-model="queryParams.roleName"
              placeholder="请输入角色名称"
              class="search-input pl-10 pr-4 py-2 w-full rounded-md border border-border bg-bg-hover focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            >
            <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-muted"></i>
          </div>
        </div>

        <!-- 状态筛选 -->
        <div>
          <label class="block text-text-secondary mb-2 text-sm font-medium">状态</label>
          <div class="search-select-wrapper">
            <el-select
              v-model="queryParams.status"
              placeholder="全部状态"
              clearable
              class="search-select w-full"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </div>
        </div>

        <!-- 占位符保持网格对齐 -->
        <div></div>
      </div>

      <!-- 高级搜索和操作按钮 -->
      <div class="mt-4 flex justify-between items-center">
        <button class="text-primary hover:text-primary-hover text-sm transition-colors">
          <i class="fas fa-sliders-h mr-1"></i>
          高级搜索
        </button>

        <!-- 操作按钮组 -->
        <div class="flex space-x-3">
          <button
            @click="resetQuery"
            class="px-4 py-2 border border-border rounded-md text-text-secondary hover:bg-bg-hover transition-colors"
          >
            重置
          </button>
          <button
            @click="handleQuery"
            class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-hover shadow-sm transition-colors"
          >
            搜索
          </button>
        </div>
      </div>
    </div>

    <SystemTable
      title="角色列表"
      :total="total"
      @page-change="handlePageChange"
      @filter="handleTableFilter"
      @export="handleExport"
      export-permission="role:export"
      v-loading="loading"
      :data="roleList"
      row-key="roleId"
      ref="tableRef"
    >
      <el-table-column prop="roleCode" label="角色代码" show-overflow-tooltip align="left" />
      <el-table-column prop="roleName" label="角色名称" show-overflow-tooltip align="left" />
      <el-table-column prop="remark" label="角色描述" show-overflow-tooltip align="left" />
      <el-table-column label="状态" width="80" align="center">
        <template #default="{ row }">
          <span
            class="status-tag"
            :class="row.status === 1 ? 'status-enabled' : 'status-disabled'"
          >
            {{ row.status === 1 ? '启用' : '禁用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" sortable show-overflow-tooltip align="left" />
      <el-table-column label="操作" fixed="right" align="center">
        <template #default="{ row }">
          <div class="table-actions">
            <button
              class="action-btn edit-btn"
              @click="handleEdit(row)"
              v-permission="'role:update'"
              title="编辑"
            >
              <i class="fas fa-edit"></i>
            </button>
            <button
              class="action-btn view-btn"
              @click="openPermissionDialog(row)"
              v-permission="'role:assign-permission'"
              title="配置权限"
            >
              <i class="fas fa-key"></i>
            </button>
            <button
              class="action-btn info-btn"
              @click="openMenuDialog(row)"
              v-permission="'role:assign-menu'"
              title="配置菜单"
            >
              <i class="fas fa-bars"></i>
            </button>
            <button
              class="action-btn delete-btn"
              @click="handleDelete(row)"
              v-permission="'role:delete'"
              title="删除"
            >
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </template>
      </el-table-column>
    </SystemTable>
  </div>

  <!-- 新增/编辑角色对话框 -->
  <el-dialog
    v-model="formVisible"
    :title="isEdit ? '编辑角色' : '新增角色'"
    width="600px"
    destroy-on-close
  >
    <el-form
      ref="roleFormRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="角色编码" prop="roleCode">
        <el-input
          v-model="formData.roleCode"
          placeholder="请输入角色编码"
          :disabled="isEdit"
        />
      </el-form-item>

      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="formData.roleName"
          placeholder="请输入角色名称"
        />
      </el-form-item>

      <el-form-item label="描述" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入角色描述"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="数据范围" prop="dataScope">
        <el-select v-model="formData.dataScope" placeholder="请选择数据范围">
          <el-option label="全部数据权限" value="1" />
          <el-option label="自定数据权限" value="2" />
          <el-option label="部门数据权限" value="3" />
          <el-option label="部门及以下数据权限" value="4" />
          <el-option label="仅本人数据权限" value="5" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 权限配置对话框 -->
  <el-dialog
    v-model="permissionDialogVisible"
    :title="`配置权限 - ${currentRoleName}`"
    width="800px"
    destroy-on-close
  >
    <div class="permission-dialog-content">
      <div class="mb-3">
        <el-alert
          title="权限说明"
          description="请选择该角色需要拥有的权限，权限将决定用户可以访问的功能"
          type="info"
          :closable="false"
        />
      </div>

      <!-- 权限筛选控制器 -->
      <div class="permission-filter mb-3">
        <div class="filter-row">
          <el-radio-group v-model="permissionViewMode" @change="onPermissionViewModeChange" class="mr-4">
            <el-radio-button label="all">全部权限</el-radio-button>
            <el-radio-button label="byMenu">按菜单分组</el-radio-button>
          </el-radio-group>

          <el-select
            v-if="permissionViewMode === 'byMenu'"
            v-model="selectedMenuForPermission"
            placeholder="选择菜单筛选权限"
            clearable
            @change="onMenuPermissionFilter"
            style="width: 200px;"
          >
            <el-option label="显示全部" value="" />
            <el-option
              v-for="menu in flatMenuList"
              :key="menu.id"
              :label="menu.menuTitle"
              :value="menu.id"
            >
              <span>{{ menu.menuTitle }}</span>
              <el-tag size="small" class="ml-2" :type="menu.menuType === 'DIR' ? 'info' : 'success'">
                {{ menu.menuType === 'DIR' ? '目录' : '菜单' }}
              </el-tag>
            </el-option>
          </el-select>
        </div>
      </div>

      <div class="tree-container" style="max-height: 400px; overflow-y: auto; border: 1px solid #e4e7ed; border-radius: 4px; padding: 10px;">
        <el-tree
          v-if="permissionDialogVisible"
          ref="permissionTreeRef"
          :data="filteredPermissionTreeData"
          node-key="id"
          show-checkbox
          :default-checked-keys="permissionCheckedKeys"
          :props="{ label: 'permissionName', children: 'children' }"
          @check="onPermissionTreeCheck"
        >
          <template #default="{ node, data }">
            <div class="tree-node-content">
              <!-- 菜单图标 -->
              <el-icon v-if="data.type === 'menu' && getIconComponent(data.menuIcon)" class="mr-1">
                <component :is="getIconComponent(data.menuIcon)" />
              </el-icon>

              <!-- 节点名称 -->
              <span class="node-label">{{ data.permissionName || data.name }}</span>

              <!-- 菜单类型标签 -->
              <el-tag
                v-if="data.type === 'menu' && data.menuType"
                size="small"
                class="ml-2"
                :type="data.menuType === 'DIR' ? 'info' : data.menuType === 'MENU' ? 'success' : 'warning'"
              >
                {{ data.menuType === 'DIR' ? '目录' : data.menuType === 'MENU' ? '菜单' : '按钮' }}
              </el-tag>

              <!-- 权限代码标签 -->
              <el-tag v-else-if="data.permissionCode && data.type !== 'menu'" size="small" class="ml-2" type="warning">
                {{ data.permissionCode }}
              </el-tag>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button @click="checkAllPermissions">全选</el-button>
        <el-button @click="uncheckAllPermissions">取消全选</el-button>
        <el-button type="primary" @click="saveRolePermissions" :loading="loading">保存权限</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 菜单配置对话框 -->
  <el-dialog
    v-model="menuDialogVisible"
    :title="`配置菜单 - ${currentRoleName}`"
    width="800px"
    destroy-on-close
  >
    <div class="menu-dialog-content">
      <div class="mb-3">
        <el-alert
          title="菜单说明"
          description="请选择该角色可以访问的菜单，菜单将决定用户可以看到的导航项"
          type="success"
          :closable="false"
        />
      </div>

      <div class="tree-container" style="max-height: 400px; overflow-y: auto; border: 1px solid #e4e7ed; border-radius: 4px; padding: 10px;">
        <el-tree
          v-if="menuDialogVisible"
          ref="menuTreeRef"
          :data="menuTreeData"
          node-key="id"
          show-checkbox
          :default-checked-keys="menuCheckedKeys"
          :props="{ label: 'menuTitle', children: 'children' }"
          @check="onMenuTreeCheck"
        >
          <template #default="{ node, data }">
            <div class="tree-node-content">
              <el-icon v-if="getIconComponent(data.menuIcon)" class="mr-1">
                <component :is="getIconComponent(data.menuIcon)" />
              </el-icon>
              <span class="node-label">{{ data.title || data.menuTitle || data.name }}</span>
              <el-tag v-if="data.menuType" size="small" class="ml-2"
                     :type="data.menuType === 'DIR' ? 'info' : data.menuType === 'MENU' ? 'success' : 'warning'">
                {{ data.menuType === 'DIR' ? '目录' : data.menuType === 'MENU' ? '菜单' : '按钮' }}
              </el-tag>
              <span class="node-path" v-if="data.routePath">{{ data.routePath }}</span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button @click="checkAllMenus">全选</el-button>
        <el-button @click="uncheckAllMenus">取消全选</el-button>
        <el-button type="primary" @click="saveRoleMenus" :loading="loading">保存菜单</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElSelect, ElOption } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete,
  Key,
  Menu
} from '@element-plus/icons-vue'
import * as ElementPlusIcons from '@element-plus/icons-vue'
import { roleApi } from '@/api/role'
import { permissionApi } from '@/api/permission'
import { menuApi } from '@/api/menu'
import type { RoleDTO } from '@/types/api'
import SystemTable from '@/components/SystemTable/index.vue'

// 响应式数据
const loading = ref(false)
const roleList = ref<RoleDTO[]>([])
const total = ref(0)

// 表单相关
const formVisible = ref(false)
const isEdit = ref(false)
const roleFormRef = ref<any>()

// 表单数据
const formData = reactive({
  id: '',
  roleCode: '',
  roleName: '',
  remark: '',
  status: 1,
  dataScope: '1'
})

const queryParams = reactive({
  current: 1,
  size: 10,
  roleName: '',
  status: undefined as number | undefined
})

// 方法
const getList = async () => {
  loading.value = true
  try {
    const response = await roleApi.queryRoles(queryParams)
    roleList.value = response.data.data
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.current = 1
  getList()
}

const resetQuery = () => {
  queryParams.roleName = ''
  queryParams.status = undefined
  queryParams.current = 1
  getList()
}

// SystemTable 事件处理
const handlePageChange = (page: number, pageSize: number) => {
  queryParams.current = page
  queryParams.size = pageSize
  getList()
}

const handleTableFilter = () => {
  // 表格筛选逻辑
  console.log('表格筛选')
}

const handleExport = () => {
  // 导出逻辑
  ElMessage.success('导出功能开发中...')
}

const handleAdd = () => {
  formVisible.value = true
  isEdit.value = false
  nextTick(() => {
    if (roleFormRef.value) {
      roleFormRef.value.resetFields()
    }
  })
  // 重置表单数据
  Object.assign(formData, {
    roleCode: '',
    roleName: '',
    remark: '',
    status: 1,
    dataScope: '1'
  })
}

const handleEdit = (row: RoleDTO) => {
  formVisible.value = true
  isEdit.value = true
  nextTick(() => {
    if (roleFormRef.value) {
      roleFormRef.value.resetFields()
    }
  })
  // 填充表单数据
  Object.assign(formData, {
    id: row.roleId,
    roleCode: row.roleCode,
    roleName: row.roleName,
    remark: (row as any).remark || '',
    status: row.status,
    dataScope: String((row as any).dataScope || '1')
  })
}

// 权限配置对话框
const permissionDialogVisible = ref(false)
const permissionTreeData = ref<any[]>([])
const filteredPermissionTreeData = ref<any[]>([])
const permissionCheckedKeys = ref<string[]>([])
const permissionHalfCheckedKeys = ref<string[]>([])
const permissionTreeRef = ref<any>()
const currentRoleId = ref<string>('')
const currentRoleName = ref<string>('')

// 权限筛选相关
const permissionViewMode = ref<'all' | 'byMenu'>('all')
const selectedMenuForPermission = ref<string>('')
const flatMenuList = ref<any[]>([])
const menuPermissionMap = ref<Map<string, any[]>>(new Map())

// 菜单配置对话框
const menuDialogVisible = ref(false)
const menuTreeData = ref<any[]>([])
const menuCheckedKeys = ref<string[]>([])
const menuHalfCheckedKeys = ref<string[]>([])
const menuTreeRef = ref<any>()

const openPermissionDialog = async (row: RoleDTO) => {
  try {
    loading.value = true
    currentRoleId.value = row.roleId as string
    currentRoleName.value = row.roleName as string
    permissionDialogVisible.value = true

    // 拉取权限树 + 角色已分配权限
    const [treeResp, rolePermResp] = await Promise.all([
      permissionApi.getPermissionTree(),
      roleApi.getRolePermissions(row.roleId as string)
    ])

    const tree = Array.isArray(treeResp.data) ? treeResp.data : []
    const rolePerms: string[] = Array.isArray(rolePermResp.data) ? rolePermResp.data : []

    // 处理权限树数据，确保有正确的字段
    const processTree = (nodes: any[]): any[] => {
      return nodes.map(node => ({
        id: node.permissionId || node.id,
        permissionName: node.permissionName || node.name,
        permissionCode: node.permissionCode || node.code,
        children: node.children ? processTree(node.children) : []
      }))
    }

    const processedTree = processTree(tree)
    permissionTreeData.value = processedTree

    console.log('权限树加载完成:', {
      原始数据: tree.length,
      处理后数据: processedTree.length,
      样例数据: processedTree.slice(0, 2)
    })

    // 构建平级菜单列表和菜单权限映射
    await buildMenuPermissionMapping()

    // 获取叶子节点的已选权限
    const checked: string[] = []
    const walk = (list: any[]) => {
      list.forEach((n: any) => {
        const nodeId = String(n.id || '')
        if (nodeId && rolePerms.includes(nodeId)) {
          // 只选中叶子节点，避免父节点自动选中
          if (!n.children || n.children.length === 0) {
            checked.push(nodeId)
          }
        }
        if (Array.isArray(n.children) && n.children.length) {
          walk(n.children)
        }
      })
    }
    walk(permissionTreeData.value)

    permissionCheckedKeys.value = Array.from(new Set(checked))
    permissionHalfCheckedKeys.value = []

    // 初始化筛选后的权限树
    updateFilteredPermissionTree()
  } catch (e) {
    console.error('加载权限树失败:', e)
    ElMessage.error('加载权限树失败')
  } finally {
    loading.value = false
  }
}

// 打开菜单配置对话框
const openMenuDialog = async (row: RoleDTO) => {
  try {
    loading.value = true
    currentRoleId.value = row.roleId as string
    currentRoleName.value = row.roleName as string
    menuDialogVisible.value = true

    // 拉取菜单树和角色已分配的菜单
    const [treeResp, roleMenuResp] = await Promise.all([
      menuApi.getMenuTree(),
      roleApi.getRoleMenus(row.roleId as string).catch(() => ({ data: [] })) // 容错处理
    ])

    const tree = Array.isArray(treeResp.data) ? treeResp.data : []
    const roleMenus: string[] = Array.isArray(roleMenuResp.data) ? roleMenuResp.data : []

    // 处理菜单树数据
    const processMenuTree = (nodes: any[]): any[] => {
      return nodes.map(node => ({
        id: node.menuId || node.id,
        menuName: node.menuName || node.name,
        menuTitle: node.title || node.menuTitle,
        menuType: node.menuType,
        menuIcon: node.menuIcon || node.icon,
        routePath: node.routePath || node.path,
        permissionCode: node.permissionCode || node.permission,
        // 修复层级显示：使用childMenus而不是children
        children: node.childMenus ? processMenuTree(node.childMenus) :
                  node.children ? processMenuTree(node.children) : []
      }))
    }

    menuTreeData.value = processMenuTree(tree)

    // 获取叶子节点的已选菜单
    const checked: string[] = []
    const walk = (list: any[]) => {
      list.forEach((n: any) => {
        const nodeId = String(n.id || '')
        if (nodeId && roleMenus.includes(nodeId)) {
          // 只选中叶子节点，避免父节点自动选中
          if (!n.children || n.children.length === 0) {
            checked.push(nodeId)
          }
        }
        if (Array.isArray(n.children) && n.children.length) {
          walk(n.children)
        }
      })
    }
    walk(menuTreeData.value)

    menuCheckedKeys.value = checked
    menuHalfCheckedKeys.value = []
  } catch (e) {
    console.error('加载菜单树失败:', e)
    ElMessage.error('加载菜单树失败')
  } finally {
    loading.value = false
  }
}

const saveRolePermissions = async () => {
  try {
    loading.value = true

    // 获取选中的权限ID（包括半选中的父节点）
    const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || []
    const halfCheckedKeys = permissionTreeRef.value?.getHalfCheckedKeys() || []
    const allSelectedIds = [...checkedKeys, ...halfCheckedKeys]

    // 转换为字符串数组并过滤掉虚拟的菜单组节点（根据后端API要求）
    const permissionIds = allSelectedIds
      .map(id => String(id))
      .filter(id => id !== '' && !id.startsWith('menu_group_')) // 过滤掉虚拟菜单组节点

    console.log('保存权限详情:', {
      原始选中: checkedKeys,
      半选中: halfCheckedKeys,
      最终权限IDs: permissionIds,
      权限数量: permissionIds.length
    })

    // 增加数据校验：如果没有选择任何权限，给出明确提示
    if (permissionIds.length === 0) {
      const result = await ElMessageBox.confirm(
        '当前没有选择任何权限，确定要移除该角色的所有权限吗？',
        '权限配置确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      if (result !== 'confirm') {
        return
      }
    }

    await roleApi.assignPermissions(currentRoleId.value, permissionIds)
    ElMessage.success(`权限配置保存成功（共${permissionIds.length}个权限）`)
    permissionDialogVisible.value = false
  } catch (e: any) {
    console.error('保存权限失败:', e)
    if (e === 'cancel') {
      // 用户取消操作，不显示错误信息
      return
    }
    ElMessage.error(e?.message || '保存权限失败')
  } finally {
    loading.value = false
  }
}

// 保存角色菜单
const saveRoleMenus = async () => {
  try {
    loading.value = true

    // 获取选中的菜单ID（包括半选中的父节点）
    const checkedKeys = menuTreeRef.value?.getCheckedKeys() || []
    const halfCheckedKeys = menuTreeRef.value?.getHalfCheckedKeys() || []
    const allSelectedIds = [...checkedKeys, ...halfCheckedKeys]

    // 转换为字符串数组（根据后端API要求）
    const menuIds = allSelectedIds.map(id => String(id)).filter(id => id !== '')

    await roleApi.assignMenus(currentRoleId.value, menuIds)
    ElMessage.success('菜单配置保存成功')
    menuDialogVisible.value = false
  } catch (e) {
    console.error('保存菜单失败:', e)
    ElMessage.error('保存菜单失败')
  } finally {
    loading.value = false
  }
}

// 全选权限
const checkAllPermissions = () => {
  const allKeys: string[] = []
  const walk = (nodes: any[]) => {
    nodes.forEach(node => {
      if (node.type !== 'menu') { // 跳过菜单组节点
        allKeys.push(String(node.id))
      }
      if (node.children && node.children.length > 0) {
        walk(node.children)
      }
    })
  }

  // 修复：使用原始权限数据而不是筛选后的数据，确保全选能选择所有权限
  const dataToWalk = permissionTreeData.value.length > 0 ? permissionTreeData.value : filteredPermissionTreeData.value
  walk(dataToWalk)

  console.log('全选权限ID列表:', allKeys)
  permissionTreeRef.value?.setCheckedKeys(allKeys)
}

// 取消全选权限
const uncheckAllPermissions = () => {
  permissionTreeRef.value?.setCheckedKeys([])
}

// 全选菜单
const checkAllMenus = () => {
  const allKeys: string[] = []
  const walk = (nodes: any[]) => {
    nodes.forEach(node => {
      allKeys.push(String(node.id))
      if (node.children && node.children.length > 0) {
        walk(node.children)
      }
    })
  }
  walk(menuTreeData.value)
  menuTreeRef.value?.setCheckedKeys(allKeys)
}

// 取消全选菜单
const uncheckAllMenus = () => {
  menuTreeRef.value?.setCheckedKeys([])
}

const onPermissionTreeCheck = (_data: any, state: any) => {
  try {
    permissionCheckedKeys.value = (state?.checkedKeys || []).map((x: any) => String(x))
    permissionHalfCheckedKeys.value = (state?.halfCheckedKeys || []).map((x: any) => String(x))
  } catch {}
}

const onMenuTreeCheck = (_data: any, state: any) => {
  try {
    menuCheckedKeys.value = (state?.checkedKeys || []).map((x: any) => String(x))
    menuHalfCheckedKeys.value = (state?.halfCheckedKeys || []).map((x: any) => String(x))
  } catch {}
}

const handleDelete = async (row: RoleDTO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${row.roleName}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await roleApi.deleteRole(row.roleId!)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 表单提交
const handleSubmit = async () => {
  try {
    if (!roleFormRef.value) return
    await roleFormRef.value.validate()

    loading.value = true

    if (isEdit.value) {
      // 编辑角色
      await roleApi.updateRole(formData.id, formData)
      ElMessage.success('角色更新成功')
    } else {
      // 新增角色
      await roleApi.createRole(formData)
      ElMessage.success('角色创建成功')
    }

    formVisible.value = false
    getList()
  } catch (error: any) {
    console.error('保存角色失败:', error)
    ElMessage.error(error?.message || '保存失败')
  } finally {
    loading.value = false
  }
}

// 表单取消
const handleCancel = () => {
  formVisible.value = false
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
}

// 表单验证规则
const formRules = {
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 50, message: '角色编码长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 权限筛选相关方法

// 构建菜单权限映射
const buildMenuPermissionMapping = async () => {
  try {
    // 使用新的API获取菜单权限映射
    const [menuResp, menuPermissionResp] = await Promise.all([
      menuApi.getMenuTree(),
      permissionApi.getMenuPermissionMap()
    ])

    const menuTree = Array.isArray(menuResp.data) ? menuResp.data : []
    const menuPermissions = menuPermissionResp.data || {}

    // ⭐ 重要：保存菜单树数据，供树状结构显示使用
    // 处理菜单树数据，统一字段名
    const processMenuTreeData = (nodes: any[]): any[] => {
      return nodes.map(node => ({
        id: node.menuId || node.id,
        menuId: node.menuId || node.id,
        menuTitle: node.title || node.menuTitle,
        menuName: node.name || node.menuName,
        menuType: node.menuType,
        menuIcon: node.menuIcon || node.icon,
        permissionCode: node.permissionCode || node.permission,
        routePath: node.routePath || node.path,
        children: node.childMenus ? processMenuTreeData(node.childMenus) :
                  node.children ? processMenuTreeData(node.children) : [],
        childMenus: node.childMenus ? processMenuTreeData(node.childMenus) :
                     node.children ? processMenuTreeData(node.children) : []
      }))
    }

    menuTreeData.value = processMenuTreeData(menuTree)

    console.log('菜单树数据已保存:', {
      原始菜单树: menuTree.length,
      处理后菜单树: menuTreeData.value.length,
      样例: menuTreeData.value.slice(0, 2)
    })

    // 构建平级菜单列表（用于筛选器）
    const flatList: any[] = []
    const addToFlatList = (nodes: any[]) => {
      nodes.forEach(node => {
        if (node.menuType === 'MENU' || node.menuType === 'DIR') {
          flatList.push({
            id: node.menuId || node.id,
            menuTitle: node.title || node.menuTitle,
            menuType: node.menuType,
            menuIcon: node.menuIcon || node.icon,
            permissionCode: node.permissionCode || node.permission
          })
        }
        if (node.childMenus && node.childMenus.length > 0) {
          addToFlatList(node.childMenus)
        } else if (node.children && node.children.length > 0) {
          addToFlatList(node.children)
        }
      })
    }
    addToFlatList(menuTreeData.value)
    flatMenuList.value = flatList

    // 使用后端返回的菜单权限映射
    const permissionMap = new Map<string, any[]>()
    Object.entries(menuPermissions).forEach(([menuId, permissions]) => {
      if (permissions && permissions.length > 0) {
        permissionMap.set(menuId, permissions)
      }
    })

    menuPermissionMap.value = permissionMap

    console.log('菜单权限映射构建成功:', {
      menuCount: flatList.length,
      mappingCount: permissionMap.size,
      totalPermissions: Object.values(menuPermissions).flat().length
    })

  } catch (error) {
    console.error('构建菜单权限映射失败:', error)

    // 降级处理：使用原有的客户端匹配逻辑
    try {
      const flatPermissions: any[] = []
      const flattenPermissions = (nodes: any[]) => {
        nodes.forEach(node => {
          flatPermissions.push(node)
          if (node.children && node.children.length > 0) {
            flattenPermissions(node.children)
          }
        })
      }
      flattenPermissions(permissionTreeData.value)

      const permissionMap = new Map<string, any[]>()
      flatMenuList.value.forEach(menu => {
        const relatedPermissions = flatPermissions.filter(perm => {
          if (!menu.permissionCode) return false
          const menuPermCode = menu.permissionCode.toLowerCase()
          const permCode = (perm.permissionCode || '').toLowerCase()

          // 匹配逻辑：权限码包含菜单的权限前缀
          const menuPrefix = menuPermCode.split(':')[0]
          return permCode.includes(menuPrefix)
        })

        if (relatedPermissions.length > 0) {
          permissionMap.set(menu.id, relatedPermissions)
        }
      })

      menuPermissionMap.value = permissionMap
      console.log('使用降级逻辑构建菜单权限映射')
    } catch (fallbackError) {
      console.error('降级逻辑也失败了:', fallbackError)
    }
  }
}

// 更新筛选后的权限树
const updateFilteredPermissionTree = () => {
  if (permissionViewMode.value === 'all') {
    filteredPermissionTreeData.value = permissionTreeData.value
  } else if (permissionViewMode.value === 'byMenu') {
    if (!selectedMenuForPermission.value) {
      // ⭐ 新功能：按菜单树状结构分组显示所有权限
      const buildMenuTreeWithPermissions = (menus: any[]): any[] => {
        return menus.map(menu => {
          const menuId = menu.menuId || menu.id
          const relatedPerms = menuPermissionMap.value.get(menuId) || []

          // 递归处理子菜单
          const childrenWithPermissions = menu.childMenus || menu.children
            ? buildMenuTreeWithPermissions(menu.childMenus || menu.children)
            : []

          // 只有当菜单有权限或有子菜单时才显示
          const hasPermissions = relatedPerms.length > 0
          const hasChildren = childrenWithPermissions.length > 0

          if (!hasPermissions && !hasChildren) {
            return null
          }

          return {
            id: `menu_group_${menuId}`,
            permissionName: menu.menuTitle || menu.title || menu.menuName,
            type: 'menu',
            menuIcon: menu.menuIcon || menu.icon,
            menuType: menu.menuType,
            children: [
              // 先显示该菜单的权限
              ...relatedPerms.map(perm => ({
                ...perm,
                id: perm.id || perm.permissionId
              })),
              // 再显示子菜单
              ...childrenWithPermissions
            ].filter(Boolean)
          }
        }).filter(Boolean)
      }

      // 从后端获取菜单树数据（保持层级结构）
      console.log('🌲 检查菜单树数据:', {
        menuTreeDataExists: !!menuTreeData.value,
        menuTreeDataLength: menuTreeData.value ? menuTreeData.value.length : 0,
        firstMenu: menuTreeData.value ? menuTreeData.value[0] : null
      })

      if (menuTreeData.value && menuTreeData.value.length > 0) {
        const treeGroupedData = buildMenuTreeWithPermissions(menuTreeData.value)

        console.log('🌲 树状结构构建结果:', {
          输入菜单数: menuTreeData.value.length,
          输出节点数: treeGroupedData.length,
          第一个节点: treeGroupedData[0],
          使用树状结构: true
        })

        if (treeGroupedData.length > 0) {
          filteredPermissionTreeData.value = treeGroupedData
          console.log('✅ 按菜单树状结构分组成功')
        } else {
          // 回退到显示所有权限
          filteredPermissionTreeData.value = permissionTreeData.value
          console.log('⚠️ 菜单树没有权限数据，回退到全部权限')
        }
      } else {
        console.warn('⚠️ 菜单树数据不可用，使用降级方案')
        // 降级：如果没有菜单树数据，使用原有的平铺方式
        const groupedData: any[] = []
        flatMenuList.value.forEach(menu => {
          const relatedPerms = menuPermissionMap.value.get(menu.id) || []
          if (relatedPerms.length > 0) {
            groupedData.push({
              id: `menu_group_${menu.id}`,
              permissionName: menu.menuTitle,
              type: 'menu',
              menuIcon: menu.menuIcon,
              children: relatedPerms.map(perm => ({
                ...perm,
                id: perm.id || perm.permissionId
              }))
            })
          }
        })
        filteredPermissionTreeData.value = groupedData.length > 0 ? groupedData : permissionTreeData.value
        console.log('使用平铺菜单分组（降级）:', {
          菜单数量: flatMenuList.value.length,
          有权限的菜单: groupedData.length
        })
      }
    } else {
      // 筛选特定菜单的权限（保持原有逻辑）
      const selectedMenu = flatMenuList.value.find(m => m.id === selectedMenuForPermission.value)
      const relatedPerms = menuPermissionMap.value.get(selectedMenuForPermission.value) || []

      if (selectedMenu && relatedPerms.length > 0) {
        filteredPermissionTreeData.value = [{
          id: `menu_group_${selectedMenu.id}`,
          permissionName: selectedMenu.menuTitle,
          type: 'menu',
          menuIcon: selectedMenu.menuIcon,
          children: relatedPerms.map(perm => ({
            ...perm,
            id: perm.id || perm.permissionId
          }))
        }]
      } else {
        // 如果选择的菜单没有权限，回退到显示所有权限
        filteredPermissionTreeData.value = permissionTreeData.value
        console.log('选择的菜单没有关联权限，回退到显示所有权限')
      }
    }
  }

  console.log('权限树筛选完成:', {
    模式: permissionViewMode.value,
    选择的菜单: selectedMenuForPermission.value,
    筛选后权限数量: filteredPermissionTreeData.value.length
  })

  // 树结构更新后，重新应用选中状态
  nextTick(() => {
    if (permissionTreeRef.value && permissionCheckedKeys.value.length > 0) {
      // 过滤出在当前树结构中有效的权限ID（排除虚拟菜单组节点）
      const validCheckedKeys = permissionCheckedKeys.value.filter(key => !key.startsWith('menu_group_'))
      permissionTreeRef.value.setCheckedKeys(validCheckedKeys)
    }
  })
}

// 权限显示模式变更
const onPermissionViewModeChange = () => {
  selectedMenuForPermission.value = ''
  updateFilteredPermissionTree()
}

// 菜单权限筛选
const onMenuPermissionFilter = () => {
  updateFilteredPermissionTree()
}

// 获取图标组件
const getIconComponent = (iconName: string | undefined) => {
  if (!iconName) return null

  // 调试：输出图标信息
  // if (import.meta.env.MODE !== 'production') {
  //   console.log('🎨 RoleIndex 图标调试:', {
  //     iconName,
  //     available: !!ElementPlusIcons[iconName as keyof typeof ElementPlusIcons]
  //   })
  // }

  return ElementPlusIcons[iconName as keyof typeof ElementPlusIcons] || null
}

// 生命周期
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.permission-filter {
  .filter-row {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
  }
}

.tree-node-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 8px;

  .node-label {
    flex: 1;
    font-weight: 500;
  }

  .node-code {
    font-size: 12px;
    color: #909399;
    background: #f5f7fa;
    padding: 2px 6px;
    border-radius: 4px;
    margin-left: 8px;
  }

  .node-path {
    font-size: 12px;
    color: #606266;
    margin-left: 8px;
  }
}

// 菜单树状结构样式优化
.permission-dialog-content {
  :deep(.el-tree-node) {
    // 菜单节点样式（虚拟节点）
    &:has([data-node-type="menu"]) {
      > .el-tree-node__content {
        background-color: #f5f7fa;
        border-left: 3px solid #409eff;
        font-weight: 600;

        &:hover {
          background-color: #ecf5ff;
        }
      }
    }

    // 权限节点缩进
    .el-tree-node__children {
      .el-tree-node__content {
        padding-left: 24px !important;
      }
    }
  }
}

.permission-dialog-content,
.menu-dialog-content {
  .tree-container {
    :deep(.el-tree-node__content) {
      height: auto;
      padding: 8px 0;
    }

    :deep(.el-tree-node__label) {
      flex: 1;
    }
  }
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-tree) {
  .el-tree-node {
    &.is-expanded > .el-tree-node__content {
      .el-tree-node__expand-icon {
        transform: rotate(90deg);
      }
    }
  }
}
</style>
